/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Text,
    LineColumn,
    InputLine,
    TextArea,
    Input,
    Select,
    Button,
    useTheme,
    Table,
    TableBody,
    TableRow,
    CCell,
    Layer,
    TableHead,
    Cell,
    SuffixInput,
    BlobInputList,
    InputDatalist,
    CheckSwitch,
    Popover,
    PopoverRefer,
    IconChevronDown, PopoverContent, PopoverDescription, MenuList, MenuItem, PopoverClose, IconX, useToast, ListFlexRow,
} from "customize-easy-ui-component";
import {
    InspectRecordLayout, InternalItemProps, SelectHookfork, useInputControlSure, useItemInputControl,
} from "../common/base";
import {useMeasureInpFilter} from "../common/hooks";
import queryString from "query-string";
import {objNestSet, tableMoveRows, tableSetInp} from "../../common/tool";
import {等级评定选} from "./editorMacr";
import {setupItemAreaRoute} from "../gantry/Periodical/orcIspConfig";
import {assertNamesUnique} from "../common/eHelper";
import {itemA结论} from "../mobilecr/editorIN";
import {itemA技术见证, itemA附设装} from "../gantry/editorDj";
import {config梯子, itemA漏磁检, itemB受力结构} from "../park/editor";
import {config观测数据, config设备概况} from "../gantry/Periodical/orcBase";
import {Each_ZdSetting, useTableEditor} from "../hook/useRepTableEditor";
import {useUppyUploadM} from "../hook/useUppyUploadM";
import {css} from "@emotion/react";
import {useContext} from "react";
import UserContext from "../../routing/UserContext";
import '@uppy/core/dist/style.min.css';
import '@uppy/dashboard/dist/style.min.css';
import '@uppy/webcam/dist/style.min.css';
import {EditStorageContext} from "../StorageContext";
import Uppy from "@uppy/core";
import Tus from "@uppy/tus";
import Webcam from "@uppy/webcam";
import {ChoosePipingUnits, IPipingUnitEntity} from "../../comp/ChoosePipingUnits";
import {useSelectCollision} from "../../hooks/useSelectCollision";


// 单线图 ：多个目的的页面组装在一块，每张图一个序号作为关联的特性表 状态管理？
const itemA单图=['单元表','单图表'];
export const SingleLineDiagram=
    React.forwardRef(({ children, show ,alone=true,repId,redId,nestMd,refWidth,rep}:InternalItemProps,  ref
    ) => {
        const {user} = useContext(UserContext);
        const toast = useToast();
        const qs= queryString.parse(window.location.search);
        const ppcode =qs?.ppcode;
        const pplix =Number(qs?.pplix);
        const dxtix =Number(qs?.dxtix);
        const {modified,setModified,} =React.useContext(EditStorageContext) as any;
        const [getInpFilter]=useMeasureInpFilter(null,itemA单图,);
        //对比同常的const {inp, setInp} = useItemInputControl({ ref });这里增加onSure可立刻修改storage的。就差发送保存给后端操作。尽量避免丢失刚刚上传的文件：类似数据库事务ACID回滚和确保完整。
        const {inp, setInp,onSure} = useInputControlSure({ ref,redId,nestMd });
        //假如用{field:'_FILE_S单线图',maxFile:200}这样上传的：界面独立管理单个图片能力不佳，没关联特性表字段的显示信息，没签名按钮。？还是单个单线图一个字段存储。
        const dxtSize= inp?.单图表?.length || 0;
        const row=undefined===inp?.单图表?.[dxtix]? dxtSize : dxtix;
        const onFinish = React.useCallback(async(forRow:number, upfile: any, del:boolean) => {
            console.log("切黄-上传控件状态dxtix=",dxtix,"forRow=",forRow, row,"row=",row );
            if(inp){             //底下俩个变量不能够采用函数以外的，依赖出问题？？导致更新会不正常的。
                //[问题] dxtix执行到这里居然可能不是当前的组件序号。 还会多次执行。
                // const dxtSize= inp?.单图表?.length || 0;
                // const row=undefined===inp?.单图表?.[dxtix]? dxtSize : dxtix;
                //立即提交storage等着save给后端！
                tableSetInp('单图表', row, inp, onSure, '_FILE_', del? undefined : upfile);
                !modified && setModified(true);
            }
        }, [row, dxtix, inp, modified,onSure,setModified]);
//inp?.[table]?.[row]?.[field]?.url
        const [uploadDom]=useUppyUploadM({repId:rep?.id, table:'单图表',
                           row: row,  inp, setInp, onFinish, liveDays:1});

        const [delNo, setDelNo] = React.useState<number>();
        const [delSize, setDelSize] = React.useState<number>(1);

        const renderRow=(row:any, index:number)=>{
            return <ListFlexRow>
                <Text>{row.code}</Text> <Text>{row.rno}</Text> <Text>{row.name}</Text> <Text>{row.start}</Text> <Text>{row.stop}</Text>
            </ListFlexRow>;
        };
        const {tableIdx,setTableIdx, selectCollision,setScoSel}=useSelectCollision({ table:inp?.单元表,
            keyMap:(a:any)=>a?.code, renderRow,init:ppcode as string, label:'从报告中选个单元：'});

        const onMulSelClickPp = React.useCallback((pp: IPipingUnitEntity) => {
            inp?.单元表?.forEach((row:any, i:number) => {
                if(row?.id===pp.id && row?.crDate==pp?.crDate){     //已经签名的单元： 特性参数也能再被变动？
                    setTableIdx(i);
                    setScoSel(undefined);
                    return;
                }
            });
        }, [inp?.单元表,setTableIdx,setScoSel]);

        //俩个分叉：没有参数 或有特性表pplix的：增加图，；  有单图dxtix的：删除 增加特性表关联，签名。
        if(undefined===inp?.单图表?.[dxtix])
            return (
                <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                                     alone={alone} label={'管道单线图-管理器'}>
                    <Text variant="h4">
                        新增加一个管道单线图的上传
                    </Text>
                    上传后在最大序号后自动新加个管理对象序号：
                    {uploadDom}
                    <hr/>
                    <Text variant="h4">
                        单线图的管理对象的删除：
                    </Text>
                    依据单线图的序号把它从报告中抹去，注意需首先删除已上传的单线图并确认。
                    <br/>
                    依据排序：把单线图的序号<Input value={delNo || 0} style={{display: 'inline-flex', width: 'unset'}}
                                                  max={1000} min={1} type={"number"}
                                                  onChange={e => setDelNo(Number(e.currentTarget.value))}/>
                    开始的，<Input value={delSize} style={{display: 'inline-flex', width: 'unset'}}
                                  max={999} min={1} type={"number"}
                                  onChange={e => setDelSize(Number(e.currentTarget.value))}/>个序号的单线图管理对象删除掉。
                    <Button intent="danger" disabled={!delNo || (delNo!-1>=inp?.单图表?.length) || delSize<=0}
                            onPress={async () => {
                                for(let i=delNo!-1; (i<delNo!+delSize-1 && i<inp?.单图表?.length); i++){
                                    if((inp?.单图表?.[i]?._FILE_?.url)){
                                        toast({
                                            title: "需首先删除已上传的单线图并确认",
                                            subtitle: "管理序号" + (i+1) + "，原图名:" + inp?.单图表?.[i]?._FILE_?.name,
                                            intent: "error"
                                        });
                                        return;
                                    }
                                }
                                const delIdx=delNo!-1;
                                inp?.单图表?.splice(delIdx, delSize);
                                for (const pipe of inp?.单元表) {
                                    if(pipe?.pic?.length>0){
                                        let newpic=[];
                                        for (const link of pipe?.pic) {
                                            if(link>=delIdx) {
                                                if (link >= delIdx + delSize) {
                                                    newpic.push(link-delSize);
                                                }
                                            }
                                            else newpic.push(link);
                                        }
                                        if(newpic.length>0)
                                            pipe.pic=newpic;        //旧的关联单线图的序号需要被修订。
                                        else
                                            pipe.pic=undefined;
                                    }
                                }
                                setInp({...inp, 单图表: inp?.单图表, 单元表: inp?.单元表});      //等效setInp({...inp})
                            }}
                    >执行</Button>删除单线图管理对象。
                </InspectRecordLayout>
            );
        else return (
            <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                                 alone={alone} label={`管道单线图${dxtix}-的管理`}>
                序号{dxtix + 1}的管道单线图的关联管理：<br/>
                {uploadDom}
                <hr/>
                签字人是谁：{inp?.单图表?.[dxtix]?.sgm?.name || ''}。<br/>
                {inp?.单图表?.[dxtix]?.sgm?.username === user?.username ?
                    <Button intent="warning"
                            onPress={async () => {
                                await tableSetInp('单图表', dxtix, inp, setInp, 'sgm', undefined);
                            }}
                    >去除签名</Button>
                    :
                    <Button intent="warning"
                            onPress={async () => {
                                const me = {username: user?.username, name: user?.person?.name};
                                await tableSetInp('单图表', dxtix, inp, setInp, 'sgm', me);
                            }}
                    >签名</Button>
                }
                <hr/>
                <Text variant="h5">对应着特性表的单元：</Text>
                首先要选择适当的管道单元：
                <InputLine label={`可直接从特性表挑选:`}>
                    <ChoosePipingUnits  field={'devs'}  jsoned={true}
                                        devices={inp?.单元表}
                                        orgDevs={inp?.单元表  as any}
                                        onSelect={(pip,index) => {
                                            onMulSelClickPp(pip);
                                        }}
                                        edit={false}
                                        pipe={{id:rep?.isp?.dev?.id, name:rep?.isp?.dev?.cod}}
                    />
                </InputLine>
                或者依管道单元编号来选定：
                {selectCollision}
                当前选定管道单元在报告管道单元表中的序号={undefined !== tableIdx ? tableIdx + 1 : '?'}，管道编号={inp?.单元表?.[tableIdx!]?.code}；
                <Button intent="success" disabled={!(inp?.单元表?.[tableIdx!]?.code)}
                        onPress={async () => {
                            let newpics=[...(inp?.单元表?.[tableIdx!]?.pic||[]), dxtix ];
                            let picnos=Array.from(new Set(newpics)).sort();
                            tableSetInp('单元表', tableIdx!, inp, setInp, 'pic', picnos);
                        }}
                >关联</Button>单线图和管道单元。
            </InspectRecordLayout>
        );
    } );

//特性表：单元{ mm sgm pic:[单线图管理对象的序号,,]}
//以上的<ChoosePipingUnits  是最为简化的只能为已经选择的多个单元再次进行特定一个单元选定的，展示挑选回调。
